﻿using System;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace Demo
{
    public class ShaderProgram
    {
        public ShaderProgram()
        {
            vertexShaderHandle = GL.CreateShader(ShaderType.VertexShader);
            fragmentShaderHandle = GL.CreateShader(ShaderType.FragmentShader);
            shaderProgramHandle = GL.CreateProgram();
        }
        public int vertexShaderHandle { get; }
        public int fragmentShaderHandle { get; }
        public int shaderProgramHandle { get;}
        public void InitShader(string vertexShaderSource, string fragmentShaderSource)
        {

            GL.ShaderSource(vertexShaderHandle, vertexShaderSource);
            GL.ShaderSource(fragmentShaderHandle, fragmentShaderSource);

            GL.CompileShader(vertexShaderHandle);
            GL.CompileShader(fragmentShaderHandle);

            string info_vshader = GL.GetShaderInfoLog(vertexShaderHandle);
            string info_fshader = GL.GetShaderInfoLog(fragmentShaderHandle);
            if (info_vshader != "")
            {
                Console.WriteLine(vertexShaderSource);
                Console.WriteLine(info_vshader);
            }
            if (info_fshader != "")
            {
                Console.WriteLine(fragmentShaderSource);
                Console.WriteLine(info_fshader);
            }

            GL.AttachShader(shaderProgramHandle, vertexShaderHandle);
            GL.AttachShader(shaderProgramHandle, fragmentShaderHandle);

            GL.LinkProgram(shaderProgramHandle);
            Console.WriteLine(GL.GetProgramInfoLog(shaderProgramHandle));
            GL.UseProgram(shaderProgramHandle);
        }
        
        public void SetupUniforms(Matrix4 Model,Matrix4 View, Matrix4 Projection)
        {
            GL.UseProgram(shaderProgramHandle);
            int umodel = GL.GetUniformLocation(shaderProgramHandle, "Model");
            int uview = GL.GetUniformLocation(shaderProgramHandle, "View");
            int uprojection = GL.GetUniformLocation(shaderProgramHandle, "Projection");
            int umvp = GL.GetUniformLocation(shaderProgramHandle, "MVP");
            Matrix4 MVP = Model * View * Projection;
            GL.UniformMatrix4(umodel, false, ref Model);
            GL.UniformMatrix4(uview, false, ref View);
            GL.UniformMatrix4(uprojection, false, ref Projection);
            GL.UniformMatrix4(umvp, false, ref MVP);
        }
    }
}
